<template>
  <div class="category">
    <div class="left">
      <van-sidebar
        v-model="activeKey"
        class="sider-bar"
      >
        <van-sidebar-item
          v-for="category in categories"
          :key="category.id"
          :title="category.name"
          @click="onChange(category.id)"
        />
      </van-sidebar>
    </div>
    <div class="right">
      <router-view />
    </div>
  </div>
</template>

<script>
import { getCategories } from '@/api/home.js'

export default {
  name: 'Category',
  data () {
    return {
      activeKey: 0,
      categories: []
    }
  },
  created () {
    // console.log('parent created...')
  },
  // keep-alive 缓存组件实例，组件激活时，触发 activated 生命周期钩子函数
  async activated () {
    // console.log('parent activated...')
    // 先获取本地缓存的分类数组
    const categories = JSON.parse(sessionStorage.getItem('categories'))
    if (categories) { // 有缓存的数组，则直接使用
      this.categories = categories.slice(1)
    } else { // 没有缓存的数组，则发送请求，然后将返回的数组缓存到 sessionStorage 中
      const p1 = getCategories()
      const categories = await p1
      // 将读取到的分类数组缓存到 sessionStorage 中
      sessionStorage.setItem('categories', JSON.stringify(categories.list))
      this.categories = categories.list.slice(1)
    }
    // this.$router.replace('/category/sub/' + this.categories[0].id)
    this.$router.push({
      name: 'sub',
      params: {
        cid: this.categories[0].id
      }
    })
  },
  methods: {
    onChange (id) {
      // 对象参数，使用 name 属性
      this.$router.push({
        name: 'sub',
        params: {
          cid: id
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
  .category {
    display: flex;
    height: 100%;

    .left {
      width: 80px;
      overflow-x: hidden;
      .sider-bar {
        width: 100%;
      }
    }

    .right {
      padding-top: 12px;
      flex: 1;
      overflow-x: hidden;
    }
  }
</style>
